import { ref, toRefs,watch } from 'vue';
import { useQuasar } from '@teld/q-components';
import useMappingProps from 't/common/hooks/useMappingProps';
import { planList } from '../mock';
import { useUserProfile } from './useUserProfile';
import {usePlanApi} from './usePlanApi';

export function useVariable(props,emit,) {
  const $q = useQuasar();
  
  const showNotify = $q.notify;
  const [mappingProps, mappingExpose] = useMappingProps(props);
  const { dataQuery, pageID, pageName, pageCode, fields,mixViewRefreshByData } = toRefs(props);
  const planName = ref('');
  const sortCode = ref('PlanOrder');
  const isSearch = ref(false);
  const modifyPlan:any = ref({});
  const currectPlan:any = ref({});
  const searchFilter = ref('');
  const queryPlanList = ref(planList);
  const targetName = ref('');
  const saveAsPlan = ref('');
  const isPublic = ref('');
  const isDefault = ref('');
  const showDialog = ref(false);
  const openSubWarning = ref(false);
  const subPlan = ref({});
  const sharePlan = ref({});
  const selectHelper = ref();
  const showShare = ref(false);
  const changePlanFlag = ref(false);
  const planIsChange = ref(false);
  const Ignore = ref(true);
  const menuContent = ref(null);
  const shareDetile = ref({});
  const showShareDetil = ref(false);
  const PortalIsChange = ref(false)
  const showPopup = ref(false)
  const  isCreate = ref(false)
  const UserProfile = {
    UserProfileKey: 'FASQuerySchema',
    UserDynamicKeys_notify: 'QueryPlan_ChangeNotice',
    UserDynamicKeys_sort: 'QueryPlan_PlanListSort',
    // UserDynamicKeys_unfolder: 'Filter_IsUnfolder',
    PageDynamicKey: 'QueryPLan_MixView_$planId',
  };
  const proxyPlan = ref('');
  const renameProxy = ref();
  const showRenameDialog = ref(false);
  const isReset = ref(false);
  const refPlan = ref();
  const queryPlan_list = ref(null);
  const isIgnore = ref(false);
  const planIsChanging = ref(false)
  const queryPlanByShareUrl = ref('')

  let dataQueryID;
  const LoadDataTime = ref(false)
  if (dataQuery.value) {
    if (dataQuery.value instanceof Object) {
      dataQueryID = ref(dataQuery.value.dataQueryID);
      LoadDataTime.value = dataQuery.value.LoadDataTime
    } else {
      try {
        dataQueryID = ref(JSON.parse(dataQuery.value).dataQueryID);
        LoadDataTime.value = JSON.parse(dataQuery.value).LoadDataTime
      } catch (error) {
        dataQueryID = ref(null);
      }
    }
  }
  if(mappingProps.planType=='1'){
    dataQueryID = ref(null);
  }
  const Variable =  {
    LoadDataTime,
    PortalIsChange,
    dataQueryID,
    UserProfile,
    showShareDetil,
    shareDetile,
    menuContent,
    Ignore,
    planIsChange,
    changePlanFlag,
    showShare,
    selectHelper,
    sharePlan,
    subPlan,
    openSubWarning,
    showDialog,
    isDefault,
    isPublic,
    saveAsPlan,
    $q,
    showNotify,
    mappingExpose,
    mappingProps,
    fields,
    pageCode,
    pageName,
    pageID,
    targetName,
    queryPlanList,
    searchFilter,
    currectPlan,
    modifyPlan,
    isSearch,
    sortCode,
    planName,
    dataQuery,
    proxyPlan ,
    renameProxy,
   showRenameDialog,
    isReset,
    refPlan ,
    queryPlan_list ,
    isIgnore,
    mixViewRefreshByData,
    planIsChanging,
    queryPlanByShareUrl,
    showPopup,
    isCreate
  };
  const {setUserProfile} = useUserProfile(UserProfile,modifyPlan,pageID)
  watch(
    () => openSubWarning.value,
    () => {
      setTimeout(() => {
        refPlan.value.focus();
      }, 400);
    },
  );
  let planChangeDelay:any = null;
  watch(
    () => planIsChange.value,
    () => {
      if (planChangeDelay) {
        window.clearTimeout(planChangeDelay);
        planChangeDelay = null;
      }
      planChangeDelay = window.setTimeout(() => {
        if (!planIsChange.value) {
          isIgnore.value = false;
        }
        emit('planBeEdit', {
          editStatus: planIsChange.value,
          hasAuthToSave:
            !(
              currectPlan.value.PlanRange ||
              (!currectPlan.value.PlanRange && currectPlan.value.IsAuth)
            ) || currectPlan.value.PlanRange == 3
              ? false
              : true,
        });
      }, 300);
    },
  );
  watch(
    () => planName.value,
    () => {
      setTimeout(() => {
        if(!refPlan.value) return
        let s = document.querySelector(
          '.queryplan_p_style' + mappingProps.instanceCode,
        );
        if (!s) {
          s = document.createElement('style');
          s.setAttribute(
            'class',
            'queryplan_p_style' + mappingProps.instanceCode,
          );
          s.innerHTML = `.q-menu.q-position-engine.scroll.plan_triangle_up::before{ left: ${refPlan.value.offsetWidth / 2}px}`;
          document.head.appendChild(s);
        } else {
          s.innerHTML = `.q-menu.q-position-engine.scroll.plan_triangle_up::before{ left: ${refPlan.value.offsetWidth / 2}px}`;
        }
      }, 10);
    },
  );
  const {getQueryPlanList} = usePlanApi(Variable,emit)
  watch(
    () => targetName.value,
    () => {
      if (targetName.value.length > 11) {
        // targetName.value = targetName.value.slice(0, 11);
        // Funcs.Notify($q.lang.selectHelper.warning, `方案名称最大长度为11个字符`, 'warning')
        // showNotify({
        //   message: `方案名称最大长度为11个字符`,
        //   type: 'warning',
        //   position: 'bottom-right'
        // });
      }
    },
  );
  watch(
    () => sortCode.value,
    async () => {
      queryPlanList.value = await getQueryPlanList();
      try {
        setUserProfile(UserProfile.UserDynamicKeys_sort, sortCode.value);
      } catch (error) {}
    },
  );
 


  return Variable
}
